<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class ProjectFollows_model extends CI_Model {
    
    public $tablename = 'hpg_project_follows';
    
    public $project_tab = 'hpg_project';
    
    public $tab_user = 'hpg_user';
    
    public function __construct()
    {
        parent::__construct();
    }
    
    public function getProjectByUid($uid){
        $query = $this->db->from($this->tablename.' as a')->select('b.id,b.project_name,a.color,a.color_type')
        ->join($this->project_tab.' as b', 'a.project_id=b.id');
        if( $uid ){
            $query->where('a.uid='.$uid);
        }
        $list = $query->get_array();
        return $list ? $list : [];
    }
    
    public function getUserByProjectIds($ids){
        $list = $this->db->from($this->tablename.' as a')->select('a.project_id,a.uid,b.user_name,b.photo')->join($this->tab_user.' as b', 'a.uid=b.id')->where_in('a.project_id', $ids)->get_array();
        if( !$list ){
            return false;
        }
        $return = [];
        foreach ($list as $v){
            $return[$v['project_id']][] = $v;
        }
        return $return;
    }
    
    public function getUidsByProjectId($id){
        $list = $this->db->from($this->tablename)->where('project_id='.$id)->select('uid')->fetchOnlyField('uid');
        return $list ? $list : [];
    }
    
    public function updateBatch($project_id, $uids){
        //查询已经添加的人员
        $exsitusers = $this->db->select('uid')->from($this->tablename)
        ->where('project_id='.$project_id)
        ->fetchOnlyField('uid');
        $del_user = array_diff($exsitusers, $uids);
        $add_user = array_diff($uids, $exsitusers);
        if( $del_user ){
            $delres = $this->db->from($this->tablename)
            ->where('project_id='.$project_id)->where_in('uid', $del_user)->delete();
        }
        if( $add_user ){
            $data = [];
            foreach ($add_user as $v){
                $data[] = ['project_id'=>$project_id, 'uid'=>$v, 'color'=>'#FF8247', 'ctime'=>$_SERVER['REQUEST_TIME']];
            }
            $addres = $this->insert_batch($data);
        }
    }
    
    public function insert_batch($list){
        if( !$list ){
            return false;
        }
        $res = $this->db->insert_batch($this->tablename, $list);
        return $res;
    }
    
    public function update($map, $data){
        if( !$map || !$data ){
            return false;
        }
        $res = $this->db->update($this->tablename, $data, $map);
        return $res;
    }
}
?>